let Task = require('../model/task')
let Task_img = require('../model/task_img')
let Company = require('../model/company')
let Task_sign = require('../model/task_sign')
let User = require('../model/user')
let userController = require('../controller/user')
let result = require('../utils/result');
let axios = require('axios');
let format = require('../utils/format.js')
let Sequelize = require('sequelize');
let sequelize = require('../config/db')
let Op = Sequelize.Op;
function TaskController(){

};

/**
 * 查询所有任务
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.findAll = async (req,res)=>{
    await Task.findAll().then(Result=>{
    res.status(200).json(result(0,'success',Result))
    }).catch(err=>{
        res.status(500).json(result(-1,'fail',err))

    });
}

/**
 * 查询所有已审核的任务
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.list = async (req,res)=>{
    await Task.findAll({where:{status:1}}).then(Result=>{
        res.status(200).json(result(0,'success',Result))
    }).catch(err=>{
        res.status(500).json(result(-1,'fail',err))

    });
}

/**
 * 首页任务
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.index = async (req,res)=>{
    await Task.findAll({where:{status:{$lt: 4},isDel:0},order: sequelize.literal('createdAt DESC')}).then(Result=>{
        res.status(200).json(result(0,'success',Result))
    }).catch(err=>{
        res.status(500).json(result(-1,'fail',err))

    });
}

TaskController.prototype.deleted=async (req,res)=>{
    await Task.findAll({where:{isDel:1},order: sequelize.literal('createdAt DESC')}).then(Result=>{
        res.status(200).json(result(0,'success',Result))
    }).catch(err=>{
        res.status(500).json(result(-1,'fail',err))

    });
}

TaskController.prototype.detail = async (req,res)=>{
    let task_id = req.body.task_id;
    let task = await Task.findOne({where:{task_id:task_id}})
    let imgs = await Task_img.findOne({where:{task_id:task_id}})
    res.status(200).json(result(0,'success',{task,imgs}))
}

/**
 * 创建任务
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.createFn = async (req,res)=>{
    let uid = req.body.uid;
    if(!uid){
        res.status(200).json(result(-1,'缺少uid'))
        return;
    }
    let user = await User.findOne({where:{uid:uid}});
    let headimgurl;
    let company;
    let company_name='';
    if(user.type ==1){
        company = await Company.findOne({where:{uid:uid}});
        company_name = company.name;
        headimgurl = company.logo;
    }else{
        headimgurl = user.headimgurl;
    }
    Task.create({
        uid:uid,
        nickname:user.nickname ,
        headimgurl:headimgurl,
        username:user.username,
        task_require:req.body.task_require,
        company_name:company_name,
        task_title:req.body.task_title,
        task_addr:req.body.task_addr,
        task_addr2:req.body.task_addr2,
        task_des:req.body.task_des,
        type:req.body.type,
        start_time:req.body.start_time,
        end_time:req.body.end_time,
        links:req.body.links,
        task_cycle:req.body.task_cycle,
        tag:req.body.tag,
        task_con:req.body.task_con,
        task_remarks:req.body.task_remarks,
        task_price:req.body.task_price,
        task_cash:req.body.task_price
    }).then(Result=>{
        Task_img.create({
            task_id:Result.task_id,
            uid:Result.uid,
            img1:req.body.img1,
            img2:req.body.img2,
            img3:req.body.img3,
        })
        axios.get('http://localhost:3000/wx/message',{params:{
                openid:user.openid,
                task_title:Result.task_title,
                task_id:Result.task_id,
                model:'tcs'
            }})
        res.status(200).json(result(0,'任务创建成功',Result))
    }).catch(err=>{
        res.status(200).json(result(-1,'任务创建失败',err.errors[0].message))
    });
}

/**
 * 删除任务
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.delete = async (req,res)=>{
    Task.update({isDel:1},{where:{task_id:req.body.task_id,isDel:0}}).then(Result=>{
        res.status(200).json(result(0,`任务id为${req.body.task_id}已成功删除`,'success'))
    }).catch(err=>{
        res.status(200).json(result(-1,`任务id为${req.body.task_id}删除失败`,'fail'))
    })
}

/**
 * 取消删除任务
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.cancelDel = async (req,res)=>{
    Task.update({isDel:0},{where:{task_id:req.body.task_id,isDel:1}}).then(Result=>{
        res.status(200).json(result(0,`任务id为${req.body.task_id}已成功删除`,'success'))
    }).catch(err=>{
        res.status(200).json(result(-1,`任务id为${req.body.task_id}删除失败`,'fail'))
    })
}


/**
 * 任务审核通过
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.pass = async (req,res)=>{
    Task.update({statu:1},{where:{uid:req.body.uid,task_id:req.body.task_id,status:0,isDel:0}}).then(Result=>{
        res.status(200).json(result(0,`任务id为${req.body.task_id}已通过审核`,'success'))
    }).catch(err=>{
        res.status(200).json(result(-1,`任务id为${req.body.task_id}审核失败`,'fail'))
    })
}


/**
 * 任务审核不通过
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.verify = async (req,res)=>{
    Task.update({statu:2},{where:{uid:req.body.uid,task_id:req.body.task_id,status:0,isDel:0}}).then(Result=>{
        res.status(200).json(result(0,`任务id为${req.body.task_id}审核为不通过`,'success'))
    }).catch(err=>{
        res.status(500).json(result(-1,`任务id为${req.body.task_id}审核失败`,'fail'))
    })
}

/**
 * 任务报名
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.sign = async (req,res)=>{
    let sigin_id =req.body.uid;
    let user = userController.findUser();
    let task = await Task.findOne({where:{task_id:req.body.task_id}});
    if(!task){
        res.status(200).json(result(-1,`查询不到该任务`,'fail'));
        return;
    };
    let sUser = await User.findOne({where:{uid:sigin_id}});
    let sigin = await Task_sign.findOne({where:{sigin_id:sigin_id,task_id:req.body.task_id}});
    if(sigin){
        Task_sign.update({ sign_cash:req.body.sign_cash },{where:{
                sigin_id:sigin_id,
                task_id:req.body.task_id,
                uid:task.uid,
            }}).then(()=>{
            User.findOne({where:{uid:sigin_id}}).then(user=>{
                axios.get('http://localhost:3000/wx/message',{params: {
                        openid: user.openid,
                        model:'signC'
                    }})
            });
            User.findOne({where:{uid:task.uid}}).then(user=>{
                axios.get('http://localhost:3000/wx/message',{params: {
                        openid: user.openid,
                        nickname:sUser.nickname,
                        model:'signT'
                    }})
            });
            res.status(200).json(result(0,'修改报名成功'));
        }).catch(()=>{
            res.status(200).json(result(-1,'报名失败',));

        })
    }else{
        Task_sign.create({
            sign_cash:req.body.sign_cash,
            sigin_id:sigin_id,
            task_id:req.body.task_id,
            uid:task.uid,
        });
        Task.update({status:3},{where:{
                uid:task.uid,task_id:req.body.task_id,status:{[Op.in]: [0,1,3]},isDel:0
            }}).then(Result=>{
            User.findOne({where:{uid:sigin_id}}).then(user=>{
                axios.get('http://localhost:3000/wx/message',{params: {
                        openid: user.openid,
                        model:'signC'
                    }})
            });
            User.findOne({where:{uid:task.uid}}).then(user=>{
                axios.get('http://localhost:3000/wx/message',{params: {
                        openid: user.openid,
                        nickname:sUser.nickname,
                        model:'signT'
                    }})
            });
            res.status(200).json(result(0,`任务id为${req.body.task_id}报名成功`,Result));

        }).catch(err=>{
            res.status(500).json(result(-1,`任务id为${req.body.task_id}报名失败`,'fail'))
        })
    };

}

/**
 * 工作台 报名中
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.jobSigning=async (req,res)=>{
    let uid= req.body.uid;
    if(!uid){
        res.status(200).json(result(-1,'缺少必要参数uid'));
        return;
    }
    let sign =  await Task_sign.findAll({where:{sigin_id:uid,isDel:0},
        order: sequelize.literal('createdAt DESC')}).then(rsp=>{
        let arr = []
       rsp.forEach(function (el,idx) {
            arr.push(el.task_id)
        })
        return arr;
    })
    let task = await Task.findAll({where:{task_id:{[Op.in]:sign}},order: sequelize.literal('createdAt DESC')})
    res.status(200).json(result(0,'success',task));
}

/**
 * 工作台 进行中
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.jobDoing=async (req,res)=>{
    let uid = req.body.uid;
    if(!uid){
        res.status(200).json(result(-1,'缺少必要参数uid'));
        return;
    };
    let task = await Task.findAll({where:{belong: uid,status:{[Op.lt]:[6]}},order: sequelize.literal('createdAt DESC')});
    if(!task){
        res.status(200).json(result(-1,'暂无数据'));
        return;
    };
    res.status(200).json(result(0,'success',task));
}

/**
 * 工作台 已完成
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.jobEnd=async (req,res)=>{
    let uid = req.body.uid;
    if(!uid){
        res.status(200).json(result(-1,'缺少必要参数uid'));
        return;
    };
    let task = await Task.findAll({where:{belong: uid,status:6},order: sequelize.literal('createdAt DESC')});
    if(!task){
        res.status(200).json(result(-1,'暂无数据'));
        return;
    };
    res.status(200).json(result(0,'success',task));
}

/**
 * 工作台 点击完成
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.jobFinish = async (req,res)=>{
    let uid = req.body.uid;
    let task_id = req.body.task_id;
    if(!uid){
        res.status(200).json(result(-1,'缺少必要参数uid'));
        return;
    };
    if(!task_id){
        res.status(200).json(result(-1,'缺少必要参数task_id'));
        return;
    };
    let task = await Task.findOne({where:{task_id:task_id}});


    User.findOne({where:{uid:task.uid}}).then(user=>{
        axios.get('http://localhost:3000/wx/message',{params: {
                openid: user.openid,
                model:'tastFO'
            }})
    });

    Task.update({status:5},{task_id:task_id});

    res.status(200).json(result(0,'您已确认完成,等待甲方确认'));

}

/**
 * 发布 报名中
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.releaseSigning = async (req,res)=>{
    let uid = req.body.uid;
    if(!uid){
        res.status(200).json(result(-1,'缺少必要参数uid'));
        return;
    }
   let task =await Task.findAll({where:{status:3,uid:uid},order: sequelize.literal('createdAt DESC')});
    res.status(200).json(result(0,'success',task));
}

TaskController.prototype.signList = async (req,res)=>{
    let uid = req.body.uid;
    let task_id = req.body.task_id;
    let task = await Task.findOne({where:{task_id:task_id,uid:uid}});
    let taskSign = await Task_sign.findAll({where:{uid:uid,task_id:task_id},order: sequelize.literal('createdAt DESC')})
    let arr = [];
    taskSign.forEach(function (el,idx) {
        arr.push(el.sigin_id)
    });
    let user = await User.findAll({where:{uid:{[Op.in]:arr}},order: sequelize.literal('createdAt DESC')})

    res.status(200).json(result(0,'success',{task,user,taskSign}));
}

/**
 * 发布 进行中
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.releaseDoing=async (req,res)=>{
    let uid = req.body.uid;
    if(!uid){
        res.status(200).json(result(-1,'缺少必要参数uid'));
        return;
    };
    let task = await Task.findAll({where:{uid: uid,status:{[Op.in]:[4,5]}},order: sequelize.literal('createdAt DESC')});
    if(!task){
        res.status(200).json(result(-1,'暂无数据'));
        return;
    };
    res.status(200).json(result(0,'success',task));
}

/**
 * 发布 点击完成
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.releaseFinish = async (req,res)=>{
    let uid = req.body.uid;
    let task_id = req.body.task_id;
    if(!uid){
        res.status(200).json(result(-1,'缺少必要参数uid'));
        return;
    };
    if(!task_id){
        res.status(200).json(result(-1,'缺少必要参数task_id'));
        return;
    };
    let task = await Task.findOne({where:{task_id:task_id}});


    User.findOne({where:{uid:task.belong}}).then(user=>{
        axios.get('http://localhost:3000/wx/message',{params: {
                openid: user.openid,
                model:'tastFT'
            }})
    });
    Task.update({status:6},{where:{uid:uid,task_id:task_id}});

    let _user = await User.findOne({where:{uid:task.belong}});
    let num = Number(_user.balance);
    let _num = num + Number(task.task_price);
    User.update({balance:_num},{where:{uid:task.belong}});
    res.status(200).json(result(0,'您已确认完成'));

}

/**
 * 发布 已完成
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
TaskController.prototype.releaseEnd=async (req,res)=>{
    let uid = req.body.uid;
    if(!uid){
        res.status(200).json(result(-1,'缺少必要参数uid'));
        return;
    };
    let task = await Task.findAll({where:{uid: uid,status:6},order: sequelize.literal('createdAt DESC')});
    if(!task){
        res.status(200).json(result(-1,'暂无数据'));
        return;
    };
    res.status(200).json(result(0,'success',task));
}


let taskController = new TaskController();
module.exports = taskController
